<!-- 商品分类 -->
 <template>
  <div class="goods-categories">
    <h3>商品分类</h3>
    <el-button type="primary" @click="addCategory">新增分类</el-button>

    <el-tree
      :data="categories"
      node-key="id"
      default-expand-all
      draggable
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
    >
      <template #default="{ node, data }">
        <span>{{ node.label }}</span>
        <el-button-group style="margin-left: 10px">
          <el-button size="small" @click.stop="editCategory(data)">编辑</el-button>
          <el-button size="small" type="danger" @click.stop="deleteCategory(data)">删除</el-button>
        </el-button-group>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const categories = ref([
  { id: 1, label: '电子产品' },
  { id: 2, label: '服装' },
  { id: 3, label: '食品' }
])

const addCategory = () => {
  ElMessageBox.prompt('请输入分类名称', '新增分类').then(({ value }) => {
    categories.value.push({ id: Date.now(), label: value })
    ElMessage.success('分类添加成功')
  })
}

const editCategory = (data) => {
  ElMessageBox.prompt('修改分类名称', '', { inputValue: data.label }).then(({ value }) => {
    data.label = value
    ElMessage.success('分类修改成功')
  })
}

const deleteCategory = (data) => {
  ElMessageBox.confirm('确定要删除该分类？', '提示').then(() => {
    categories.value = categories.value.filter(c => c.id !== data.id)
    ElMessage.success('分类删除成功')
  })
}

const allowDrop = (draggingNode, dropNode, type) => {
  return type !== 'inner'
}

const handleDrop = () => {
  ElMessage.info('分类已重新排序')
}
</script>